package yjj.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import yjj.model.security.LoginUser;
import yjj.system.entity.Role;
import yjj.system.entity.User;
import yjj.system.service.*;
import yjj.utils.MyBeanUtil;
import yjj.utils.RedisUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    @Autowired
    PermissionService permissionService;
    @Autowired
    RolePermissionService rolePermissionService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    RoleService rolService;

    @Autowired
    UserService userService;

    @Autowired
    UserDeptService userDeptService;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 根据用户名，封装用户信息，包括权限和角色
     * @param username 用户名
     * @return
     */
    @Override
    public LoginUser login(String username) {
        LoginUser loginUser = new LoginUser();
        //先从用户表中查出来
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userService.getOne(queryWrapper);
        MyBeanUtil.mergeProperties(user, loginUser);
        String userId = user.getUserId();
        //查询用户角色
        String roleId= userRoleService.getRoleByUserId(userId);
        loginUser.setRoleIdList(Arrays.asList(roleId));
        Role role = rolService.getById(roleId);
        //将角色放入权限中
        List<SimpleGrantedAuthority> authorities= Arrays.asList(new SimpleGrantedAuthority(role.getRoleCode()));
        loginUser.setAuthorities(authorities);
        loginUser.setAuthorityStrings(authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()));
//        System.out.println("authorities = " + authorities);
//        System.out.println("logUser的权限 = " + loginUser.getAuthorities());

        //查询用户部门
        List<String> deptIds = userDeptService.getDeptIdsByUserId(userId, user.getTenantId());
        loginUser.setDeptIdList(deptIds);
        return loginUser;
    }
}
